/** 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.free.i;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

/** 
 * Utility functions
 * @author stefano
 */
public class CommonFunctions {

	/**
	 * This class must not be instantiated, only static calls
	 */
	private CommonFunctions(){
		
	}
	
	/**
     * Retrieve from the classpath of this classloader, the path for the jndi provider properties
	 * @param fileName is the file to load properties from
     * @return the complete path for the file name passed, null if missing
     */
    public static final String getConfigFileFromClasspath(String fileName){
        
        URL configurationUrl = Thread.currentThread().getContextClassLoader().getResource(fileName);
        
        String absoluteConfigurationFile = null;
        if(configurationUrl == null){
           return absoluteConfigurationFile;
        }
        absoluteConfigurationFile = configurationUrl.getFile();
        return absoluteConfigurationFile;
    }
	
	/**
     * @param fileName is the name of the file to load properties from
     * @return a properties object loaded, or null if something goes wrong
     * @throws IOException
     * @throws FileNotFoundException
     * @throws IllegalArgumentException
     * @throws SecurityException 
     */
    public static final Properties loadProperties(String fileName) throws IOException, FileNotFoundException, IllegalArgumentException, SecurityException {
        
        Properties properties = new Properties();
        FileInputStream fileInputStream= null;
        try{
            fileInputStream = new FileInputStream(fileName);
            properties.load(fileInputStream);
        }finally{
                 try{
                     if(fileInputStream != null){
                        fileInputStream.close();    
                     }
                 }catch(Exception exc){
                        throw (new IOException("Unable to close file input stream"));
                 }
        }
        return properties;
    }
	
}
